<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>springboot conditional 注解 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="@Conditional满足指定条件的时候才将某个 bean 加载到应用上下文中. 比如 FreemarkerAutoConfiguration 这个自动化配置类的定义如下： 1234567@ConditionalOnClass(ThreadPoolTaskScheduler.class)@Configuration@EnableConfigurationProperties(TaskSchedu">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot conditional 注解">
<meta property="og:url" content="https://flyingzc.github.io/articles/springboot/springboot04-conditional.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="@Conditional满足指定条件的时候才将某个 bean 加载到应用上下文中. 比如 FreemarkerAutoConfiguration 这个自动化配置类的定义如下： 1234567@ConditionalOnClass(ThreadPoolTaskScheduler.class)@Configuration@EnableConfigurationProperties(TaskSchedu">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2020-06-30T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.215Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="springboot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "springboot conditional 注解",
  "url": "https://flyingzc.github.io/articles/springboot/springboot04-conditional.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2020-06-30T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.215Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/springboot/springboot04-conditional.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'springboot conditional 注解',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">springboot conditional 注解</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">springboot conditional 注解</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-06-30T16:00:00.000Z" title="发表于 2020-07-01 00:00:00">2020-07-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.215Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/spring-boot/">spring-boot</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="Conditional"><a href="#Conditional" class="headerlink" title="@Conditional"></a>@Conditional</h1><p>满足指定条件的时候才将某个 bean 加载到应用上下文中.</p>
<p>比如 FreemarkerAutoConfiguration 这个自动化配置类的定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ConditionalOnClass(ThreadPoolTaskScheduler.class)</span><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@EnableConfigurationProperties(TaskSchedulingProperties.class)</span><br><span class="hljs-meta">@AutoConfigureAfter(TaskExecutionAutoConfiguration.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TaskSchedulingAutoConfiguration</span> &#123;<br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>这个自动化配置类被 @ConditionalOnClass 条件注解修饰,</p>
<p>这个条件注解存在的意义在于判断类加载器中是否存在 ThreadPoolTaskScheduler 这个类,</p>
<p>如果存在的话会在 Spring 容器中加载这个 TaskSchedulingAutoConfiguration 配置类, 否则不会加载.</p>
<h1 id="ConditionalOnXxxx"><a href="#ConditionalOnXxxx" class="headerlink" title="@ConditionalOnXxxx"></a>@ConditionalOnXxxx</h1><p>Spring Boot 在 @Conditional 注解的基础上进行了细化，无需自己实现 Condition 接口，只需要使用预定义好的 @ConditionalOnXxxx 类，如果验证通过，就会注册对应的 bean.</p>
<p>这些注解都定义在 org.springframework.boot.autoconfigure.condition 包下.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java">ConditionalOnBean<br>ConditionalOnClass<br>ConditionalOnCloudPlatform<br>ConditionalOnExpression<br>ConditionalOnJava<br>ConditionalOnJndi<br>ConditionalOnMissingBean<br>ConditionalOnMissingClass<br>ConditionalOnNotWebApplication<br>ConditionalOnProperty<br>ConditionalOnResource<br>ConditionalOnSingleCandidate<br>ConditionalOnWebApplication<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Conditional(OnBeanCondition.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> ConditionalOnBean &#123;<br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="spring-boot-Condition-注解对应处理的-Conditional-类"><a href="#spring-boot-Condition-注解对应处理的-Conditional-类" class="headerlink" title="spring-boot Condition 注解对应处理的 Conditional 类"></a>spring-boot Condition 注解对应处理的 Conditional 类</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java">Condition (org.springframework.context.annotation)<br>    ConfigurationCondition (org.springframework.context.annotation)<br>        AbstractNestedCondition (org.springframework.boot.autoconfigure.condition)<br>        AllNestedConditions (org.springframework.boot.autoconfigure.condition)<br>        NoneNestedConditions (org.springframework.boot.autoconfigure.condition)<br>        AnyNestedCondition (org.springframework.boot.autoconfigure.condition)<br>        OnBeanCondition (org.springframework.boot.autoconfigure.condition)<br></code></pre></td></tr></table></figure>

<h2 id="Condition-接口"><a href="#Condition-接口" class="headerlink" title="Condition 接口"></a>Condition 接口</h2><h2 id="ConfigurationCondition-接口"><a href="#ConfigurationCondition-接口" class="headerlink" title="ConfigurationCondition 接口"></a>ConfigurationCondition 接口</h2><p>多了一个 getConfigurationPhase() 方法, 也就是 条件注解的生效阶段. 只有在 ConfigurationPhase 中定义的两种阶段下才会生效.</p>
<h2 id="SpringBootCondition"><a href="#SpringBootCondition" class="headerlink" title="SpringBootCondition"></a>SpringBootCondition</h2><p>SpringBoot 中所有条件注解对应的条件类都继承这个抽象类.</p>
<h2 id="OnClassCondition"><a href="#OnClassCondition" class="headerlink" title="OnClassCondition"></a>OnClassCondition</h2><p>@ConditionalOnClass 或者 @ConditionalOnMissingClass 注解对应的条件类是 OnClassCondition</p>
<h1 id="入口"><a href="#入口" class="headerlink" title="入口"></a>入口</h1><p>1.ComponentScan 扫描 basePackage 下的 components 的时候, 会调用 isConditionMatch(metadataReader) 判断该 component 是否条件匹配. 通过调用 conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata()) 判断是否要 skip 该 component.<br>2.&#x2F;&#x2F; TODO</p>
<h1 id="调用"><a href="#调用" class="headerlink" title="调用"></a>调用</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">conditionEvaluator.shouldSkip()<br>1. 判断必须有 @Conditional 注解<br>2. 判断是否有 phase<br>3. 通过 metadata 获取该类上的所有 Conditional 注解<br>4. 遍历通过 conditionClassName 获取对应的 Condition 类<br>5. 对 conditions 排序<br>6. 遍历 conditions, 若是 ConfigurationCondition 类型, 调用 getConfigurationPhase() 方法, 调用 condition.matches() 方法<br>    SpringBootCondition.matches()<br>    1.getClassOrMethodName() 从 metadata 中获取类名或者方法名 (条件注解可以作用的类或者方法上)<br>    2.getMatchOutcome(): 抽象方法, 具体子类实现. ConditionOutcome 记录了匹配结果 和 log 信息<br>        由具体的 Condition 接口的实现类实现该逻辑, 如 OnClassCondition, OnExpressionCondition 等<br>        // OnClassCondition.getMatchOutcome() 参见 下面逻辑<br>    3.logOutcome(): 打印 匹配信息 日志<br>    4.recordEvaluation(): 记录 匹配信息 结果<br>    5.outcome.isMatch(): 返回是否匹配结果<br></code></pre></td></tr></table></figure>

<h1 id="OnClassCondition-getMatchOutcome"><a href="#OnClassCondition-getMatchOutcome" class="headerlink" title="OnClassCondition.getMatchOutcome()"></a>OnClassCondition.getMatchOutcome()</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> ConditionOutcome <span class="hljs-title function_">getMatchOutcome</span><span class="hljs-params">(ConditionContext context,</span><br><span class="hljs-params">        AnnotatedTypeMetadata metadata)</span> &#123;<br>    <span class="hljs-type">ClassLoader</span> <span class="hljs-variable">classLoader</span> <span class="hljs-operator">=</span> context.getClassLoader();<br>    <span class="hljs-type">ConditionMessage</span> <span class="hljs-variable">matchMessage</span> <span class="hljs-operator">=</span> ConditionMessage.empty();<br>    List&lt;String&gt; onClasses = getCandidates(metadata, ConditionalOnClass.class); <span class="hljs-comment">// 1.ConditionalOnClass 注解处理. 获取类上 @ConditionalOnClass 注解里的条件值. 如从 @ConditionalOnClass(&#123; Servlet.class, ServerContainer.class &#125;) 中获取 Servlet.class, ServerContainer.class</span><br>    <span class="hljs-keyword">if</span> (onClasses != <span class="hljs-literal">null</span>) &#123;<br>        List&lt;String&gt; missing = filter(onClasses, ClassNameFilter.MISSING,<br>                classLoader); <span class="hljs-comment">// 判断条件类是否存在, 不存在的添加到 missing 里</span><br>        <span class="hljs-keyword">if</span> (!missing.isEmpty()) &#123; <span class="hljs-comment">// 有不存在的条件</span><br>            <span class="hljs-keyword">return</span> ConditionOutcome<br>                    .noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)<br>                            .didNotFind(<span class="hljs-string">&quot;required class&quot;</span>, <span class="hljs-string">&quot;required classes&quot;</span>)<br>                            .items(Style.QUOTE, missing)); <span class="hljs-comment">// 不匹配 condition</span><br>        &#125;<br>        matchMessage = matchMessage.andCondition(ConditionalOnClass.class)<br>                .found(<span class="hljs-string">&quot;required class&quot;</span>, <span class="hljs-string">&quot;required classes&quot;</span>).items(Style.QUOTE,<br>                        filter(onClasses, ClassNameFilter.PRESENT, classLoader)); <span class="hljs-comment">// 匹配 condition</span><br>    &#125;<br>    List&lt;String&gt; onMissingClasses = getCandidates(metadata,<br>            ConditionalOnMissingClass.class); <span class="hljs-comment">// 2. ConditionalOnMissingClass 注解处理</span><br>    <span class="hljs-keyword">if</span> (onMissingClasses != <span class="hljs-literal">null</span>) &#123;<br>        List&lt;String&gt; present = filter(onMissingClasses, ClassNameFilter.PRESENT,<br>                classLoader);<br>        <span class="hljs-keyword">if</span> (!present.isEmpty()) &#123;<br>            <span class="hljs-keyword">return</span> ConditionOutcome.noMatch(<br>                    ConditionMessage.forCondition(ConditionalOnMissingClass.class)<br>                            .found(<span class="hljs-string">&quot;unwanted class&quot;</span>, <span class="hljs-string">&quot;unwanted classes&quot;</span>)<br>                            .items(Style.QUOTE, present));<br>        &#125;<br>        matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class)<br>                .didNotFind(<span class="hljs-string">&quot;unwanted class&quot;</span>, <span class="hljs-string">&quot;unwanted classes&quot;</span>)<br>                .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING,<br>                        classLoader));<br>    &#125;<br>    <span class="hljs-keyword">return</span> ConditionOutcome.match(matchMessage);<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">对 ConditionalOnClass 和 ConditionalOnMissingClass 注解的处理.<br>1. 对 ConditionalOnClass 注解的处理<br>    1. 获取类上 @ConditionalOnClass 注解里的条件值. 如从 @ConditionalOnClass(&#123;Servlet.class, ServerContainer.class&#125;) 中获取 Servlet.class, ServerContainer.class<br>    2.filter(onClasses, ClassNameFilter.MISSING, classLoader) 通过 ter.MISSING 这个 filter 过滤出不存在的类 (即通过 classLoader 加载不到)<br>    3. 返回是否匹配结果<br>2. 对 ConditionalOnMissingClass 注解的处理<br>    逻辑同上<br></code></pre></td></tr></table></figure>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/springboot/springboot04-conditional.html">https://flyingzc.github.io/articles/springboot/springboot04-conditional.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/springboot/">springboot</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/springboot/springboot01-build.html" title="idea搭建spring-boot环境"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-19</div><div class="info-item-2">idea搭建spring-boot环境</div></div><div class="info-2"><div class="info-item-1">idea搭建spring-boot环境显示taggit tag 选择 v2.1.5.RELEASE 版本,这是我们项目里现在在用的版本,还比较新,最新的目前是 2.3.0. 拉自己的分支 建立我自己的分支,以后代码注释都写在这个分支上.v2.1.5.RELEASE-zc  git checkout -b v2.1.5.RELEASE-zc v2.1.5.RELEASE  v2.1.5.RELEASE 这个版本是可以选择 maven 或 gradle 构建的,我这里选的maven.  工程依赖的jar包很多,大概要下个半小时多.  将本地分支推到远程git push origin v2.1.5.RELEASE-zc  建立关联git push –set-upstream origin v2.1.5.RELEASE-zc   看看代码量spring-boot 总共代码45w行,纯代码 27w 行. idea attach sourceidea 的配置最终都落到 .idea 下的 xml 里,搜索 springboot 的 maven 配置文件,修改里面的...</div></div></div></a><a class="pagination-related" href="/articles/springboot/springboot02-start.html" title="spring-boot启动流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-24</div><div class="info-item-2">spring-boot启动流程</div></div><div class="info-2"><div class="info-item-1">spring-boot 启动 spingboot-start SpringApplication构造方法 使用 SpringFactoriesLoader 在 classpath 中查找并加载所有可用的 ApplicationContextInitializer 使用 SpringFactoriesLoader 在 classpath 中查找并加载所有可用的 ApplicationListener 通过stackTrace里的main方法查找启动类   SpringApplication.run() 创建StopWatch计时器 通过 SpringFactoriesLoader 查找并加载 SpringApplicationRunListener 列表,调用 SpringApplicationRunListener.started() 方法 创建Environment configureEnvironment() listeners.environmentPrepared(): 广播 ApplicationEnvironmentPreparedEvent...</div></div></div></a><a class="pagination-related" href="/articles/springboot/springboot05-tomcat.html" title="springboot对接tomcat"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-07</div><div class="info-item-2">springboot对接tomcat</div></div><div class="info-2"><div class="info-item-1">springboot对接tomcat调用的地方在 ServletWebServerApplicationContext 里. 创建 webServergetWebServer:166, TomcatServletWebServerFactory (org.springframework.boot.web.embedded.tomcat)createWebServer:181, ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)onRefresh:154, ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)refresh:543, AbstractApplicationContext (org.springframework.context.support)refresh:142, ServletWebServerApplicationContext...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Conditional"><span class="toc-number">1.</span> <span class="toc-text">@Conditional</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#ConditionalOnXxxx"><span class="toc-number">2.</span> <span class="toc-text">@ConditionalOnXxxx</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#spring-boot-Condition-%E6%B3%A8%E8%A7%A3%E5%AF%B9%E5%BA%94%E5%A4%84%E7%90%86%E7%9A%84-Conditional-%E7%B1%BB"><span class="toc-number">3.</span> <span class="toc-text">spring-boot Condition 注解对应处理的 Conditional 类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Condition-%E6%8E%A5%E5%8F%A3"><span class="toc-number">3.1.</span> <span class="toc-text">Condition 接口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ConfigurationCondition-%E6%8E%A5%E5%8F%A3"><span class="toc-number">3.2.</span> <span class="toc-text">ConfigurationCondition 接口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SpringBootCondition"><span class="toc-number">3.3.</span> <span class="toc-text">SpringBootCondition</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#OnClassCondition"><span class="toc-number">3.4.</span> <span class="toc-text">OnClassCondition</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%A5%E5%8F%A3"><span class="toc-number">4.</span> <span class="toc-text">入口</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%B0%83%E7%94%A8"><span class="toc-number">5.</span> <span class="toc-text">调用</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#OnClassCondition-getMatchOutcome"><span class="toc-number">6.</span> <span class="toc-text">OnClassCondition.getMatchOutcome()</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>